package com.phonemap.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONObject;


import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.search.Document;
import com.google.appengine.api.search.Field;
import com.phonemap.common.Constants;
import com.phonemap.search.SearchIndexManager;


public class ImportUserIntoIndex {
public static Logger myLogger = Logger.getLogger(ImportUserIntoIndex.class.getName());
	
	/**
	 * This method is invoked via the '/importindex' endpoint. It reads the JSON data file and invokes the processEmployees method.
	 */

//	public static void loadData() {
//		try {
//			BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(Constants.SAMPLE_EMPLOYEES_DATA_FILE)));
//			StringBuffer SB = new StringBuffer();
//			String nextLine;
//			while ((nextLine = rdr.readLine()) != null) {
//				SB.append(nextLine);
//			}
//			processEmployees(SB.toString());
//			rdr.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	/**
	 * It will parse the JSON data file and for each of the Employee Records, it will do the following:
	 * 1. Create a Document Object with each attribute of the Document object populated accordingly.
	 * 2. By defining these attributes, the Search can function on any of these fields via a simple Text Term
	 * 3. Each Document is then added to the index via the SearchIndexManager method
	 * @param employeesJSONData String value of the JSON Employees data
	 * @throws Exception
	 */
	public static void processEmployees(String employeesJSONData) throws Exception {
		JSONObject feedData = new JSONObject(employeesJSONData);
		JSONArray employeeFeeds = feedData.getJSONArray("Employees");
		for (int i = 0; i < employeeFeeds.length(); i++) {
			JSONObject employeeFeed = (JSONObject) employeeFeeds.get(i);
			String userId = employeeFeed.getString("userId");
			String jobTitleName = employeeFeed.getString("jobTitleName");
			String firstName = employeeFeed.getString("firstName");
			String lastName = employeeFeed.getString("lastName");
			String preferredFullName = employeeFeed.getString("preferredFullName");
			String employeeCode = employeeFeed.getString("employeeCode");
			String region = employeeFeed.getString("region");
			String phoneNumber = employeeFeed.getString("phoneNumber");
			String emailAddress = employeeFeed.getString("emailAddress");
			try {
				if (!userId.isEmpty()) {

					//Build a Document Object
					//Add all the attributes on which search can be done
					Document newDoc = Document.newBuilder().setId(userId)
							.addField(Field.newBuilder().setName("userId").setText(userId))
							.addField(Field.newBuilder().setName("jobTitleName").setText(jobTitleName))
							.addField(Field.newBuilder().setName("firstName").setText(firstName))
							.addField(Field.newBuilder().setName("lastName").setText(lastName))
							.addField(Field.newBuilder().setName("preferredFullName").setText(preferredFullName))
							.addField(Field.newBuilder().setName("employeeCode").setText(employeeCode))
							.addField(Field.newBuilder().setName("region").setText(region))
							.addField(Field.newBuilder().setName("phoneNumber").setText(phoneNumber))
							.addField(Field.newBuilder().setName("emailAddress").setText(emailAddress)).build();
					
					//Add the Document instance to the Search Index
					SearchIndexManager.INSTANCE.indexDocument(Constants.USER_INDEX_NAME, newDoc);
                } 
				else {
                    	throw new Exception("userId field is empty");
                }
			} catch (Exception ex) {
				myLogger.warning("Could not process Record for User : " + preferredFullName + ".Reason : " + ex.getMessage());
			}
		}
	}
	
	/**
	 * It will parse the JSON data file and for each of the User Records, it will do the following:
	 * 1. Create a Document Object with each attribute of the Document object populated accordingly.
	 * 2. By defining these attributes, the Search can function on any of these fields via a simple Text Term
	 * 3. Each Document is then added to the index via the SearchIndexManager method
	 * @param usersJSONData String value of the JSON Users data
	 * @throws Exception
	 */
	public static void processUsers(String usersJSONData) throws Exception {
		JSONObject feedData = new JSONObject(usersJSONData);
		JSONArray userFeeds = feedData.getJSONArray("Users");
		for (int i = 0; i < userFeeds.length(); i++) {
			JSONObject userFeed = (JSONObject) userFeeds.get(i);
			String userId = userFeed.getString("id");
			String fullname = userFeed.getString("fullname");
			String link = userFeed.getString("link");
			String birthday = userFeed.getString("birthday");
			String interested_in = userFeed.getString("interested_in"); 
			String gender = userFeed.getString("gender");
			String relationship_status = userFeed.getString("relationship_status");
			String timezone = userFeed.getString("timezone");
			String locale = userFeed.getString("locale");
			String verified = userFeed.getString("verified");
			String email = userFeed.getString("email");
			String updated_time = userFeed.getString("updated_time");
			String username = userFeed.getString("username");
			String position_time = userFeed.getString("position_time");
			String latitude = userFeed.getString("latitude");
			String longitude = userFeed.getString("longitude");
			String phone = userFeed.getString("phone");
			try {
				if (!userId.isEmpty()) {

					//Build a Document Object
					//Add all the attributes on which search can be done
					Document newDoc = Document.newBuilder().setId(userId)
							.addField(Field.newBuilder().setName("userId").setText(userId))
							.addField(Field.newBuilder().setName("fullname").setText(fullname))
							.addField(Field.newBuilder().setName("link").setText(link))
							.addField(Field.newBuilder().setName("birthday").setText(birthday))
							.addField(Field.newBuilder().setName("interested_in").setText(interested_in))
							.addField(Field.newBuilder().setName("relationship_status").setText(relationship_status))
							.addField(Field.newBuilder().setName("gender").setText(gender))
							.addField(Field.newBuilder().setName("email").setText(email))
							.addField(Field.newBuilder().setName("timezone").setText(timezone))
							.addField(Field.newBuilder().setName("locale").setText(locale))
							.addField(Field.newBuilder().setName("verified").setText(verified))
							.addField(Field.newBuilder().setName("updated_time").setText(updated_time))
							.addField(Field.newBuilder().setName("username").setText(username))
							.addField(Field.newBuilder().setName("latitude").setText(latitude))
							.addField(Field.newBuilder().setName("longitude").setText(longitude))
							.addField(Field.newBuilder().setName("position_time").setText(position_time))
							.addField(Field.newBuilder().setName("phone").setText(phone)).build();
					
					//Add the Document instance to the Search Index
					SearchIndexManager.INSTANCE.indexDocument(Constants.USER_INDEX_NAME, newDoc);
                } 
				else {
                    	throw new Exception("userId field is empty");
                }
			} catch (Exception ex) {
				myLogger.warning("Could not process Record for User : " + fullname + ".Reason : " + ex.getMessage());
			}
		}
	}
	
	
}
